package com.tjbank.cssys.web.service;


import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tjbank.cssys.domain.*;
import com.tjbank.cssys.web.util.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PeopleCallService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private CkFeedBackConfigService ckFeedBackConfigService;
    @Autowired
    private CkFeedBackService ckFeedBackService;
    @Autowired
    private CkOrderRecoveryDataService ckOrderRecoveryDataService;
    @Autowired
    private CkStopNoticePersonService ckStopNoticePersonService;
    @Autowired
    private CkOrderNotDialedService ckOrderNotDialedService;
    @Autowired
    private CkOrderMissedFrequencyService ckOrderMissedFrequencyService;
    @Autowired
    private CkOrderAchievementFormService ckOrderAchievementFormService;

    protected static final Logger logger = LoggerFactory.getLogger(PeopleCallService.class);
    static Date date = new Date();
    static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static String format = simpleDateFormat.format(date);

    /**
     *
     * @param jsonStr
     */
    public void peopleCallService(String jsonStr) throws ParseException {
        logger.info("人工客服数据处理，参数：params="+ JSONUtils.toJSONString(jsonStr));
        logger.info("转换人工客服参数开始");
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        Object peopleCall = jsonObject.get("人工外呼");
        List<CkOrderRecoveryData> ckOrderRecoveryDatas = JSONObject.parseArray(JSON.toJSONString(peopleCall), CkOrderRecoveryData.class);
        logger.info("转换人工客服参数结束");
        logger.info("获取反馈码分类开始");

        Map feedBackConfigMap=null;
        if (redisService.hasKey("feedBackConfig")) {
            Object feedBackConfig = redisService.get("feedBackConfig");
            feedBackConfigMap = JSON.parseObject(JSON.toJSONString(feedBackConfig), Map.class);
        } else {
            feedBackConfigMap = ckFeedBackConfigService.selectList();
        }
        logger.info("获取反馈码分类结束");

        logger.info("数据分类开始");
        //已经拨打
        List<CkOrderRecoveryData> ckOrderRecoveryDataList = new ArrayList<>();
        //未拨打
        List<CkOrderNotDialed> ckOrderNotDialedList = new ArrayList<>();
        //停催
        List<CkStopNoticePerson> ckStopNoticePeople1=new ArrayList<>();
        //停催反馈码
        Object stopCkFeedbackConfigTableObject = feedBackConfigMap.get("停催");
        CkFeedbackConfigTable stopCkFeedbackConfigTable = JSON.parseObject(JSON.toJSONString(stopCkFeedbackConfigTableObject), CkFeedbackConfigTable.class);
        String stopNumbers = stopCkFeedbackConfigTable.getNumbers();
        //失联
        List<CkStopNoticePerson> ckStopNoticePeople2=new ArrayList<>();
        //失联反馈码
        Object missCkFeedbackConfigTableObject = feedBackConfigMap.get("失联");
        CkFeedbackConfigTable missCkFeedbackConfigTable = JSONObject.parseObject(JSON.toJSONString(missCkFeedbackConfigTableObject),CkFeedbackConfigTable.class);
        String missNumbers = missCkFeedbackConfigTable.getNumbers();
        //分类规则开始
        ckOrderRecoveryDatas.stream().forEach(ckOrderRecoveryData -> {
            ckOrderRecoveryData.setNotificationMethod((byte)3);
            ckOrderRecoveryData.setDataTime(format);
            String feedbackCode = ckOrderRecoveryData.getFeedbackCode();
            //判断已接听或者未接听
            if (StringUtils.isNotEmpty(feedbackCode)) {
                ckOrderRecoveryDataList.add(ckOrderRecoveryData);
                //判断停催还是失联状态
                if (stopNumbers.contains(feedbackCode)) {
                    CkStopNoticePerson ckStopNoticePerson = new CkStopNoticePerson();
                    BeanUtils.copyProperties(ckOrderRecoveryData,ckStopNoticePerson);
                    ckStopNoticePerson.setType((byte)1);
                    ckStopNoticePerson.setDivisionMode((byte)1);
                    ckStopNoticePerson.setIsDelete((byte)0);

                    ckStopNoticePeople1.add(ckStopNoticePerson);
                } else if (missNumbers.contains(feedbackCode)){
                    CkStopNoticePerson ckStopNoticePerson = new CkStopNoticePerson();
                    BeanUtils.copyProperties(ckOrderRecoveryData,ckStopNoticePerson);
                    ckStopNoticePerson.setType((byte)2);
                    ckStopNoticePerson.setDivisionMode((byte)1);
                    ckStopNoticePerson.setIsDelete((byte)0);
                    ckStopNoticePeople2.add(ckStopNoticePerson);
                }
            } else {
                CkOrderNotDialed ckOrderNotDialed = new CkOrderNotDialed();
                BeanUtils.copyProperties(ckOrderRecoveryData,ckOrderNotDialed);
                ckOrderNotDialedList.add(ckOrderNotDialed);
            }
        });
        logger.info("数据分类结束");
        logger.info("查询所有失联单并对失联单分类开始");
        //不重复的已失联案件号
        Set<String> serialNumberList = new HashSet<>();
        //map中存储案件所对应的所有bean
        Map<String, List<CkStopNoticePerson>> ckStopNoticePeopleMap = new HashMap<>();
        //案件号所对应的list
        List<CkStopNoticePerson> ckStopNoticePeopleList = ckStopNoticePersonService.findOutOfContactAll();
        for (CkStopNoticePerson ckStopNoticePerson : ckStopNoticePeopleList) {
            String serialNumber = ckStopNoticePerson.getSerialNumber();
            serialNumberList.add(serialNumber);
            List<CkStopNoticePerson> ckStopNoticePeoples=null;
            if (ckStopNoticePeopleMap.get(serialNumber) == null) {
                ckStopNoticePeoples = new ArrayList<>();
            } else {
                ckStopNoticePeoples=ckStopNoticePeopleMap.get(serialNumber);
            }
            ckStopNoticePeoples.add(ckStopNoticePerson);
            ckStopNoticePeopleMap.put(serialNumber,ckStopNoticePeoples);
        }
        logger.info("查询所有失联单并对失联单分类结束");
        logger.info("判断失联表中是否出现成功联系开始");
        //存储失联状态重新获取到不失联list,在已失联表中删除
        List<CkStopNoticePerson> contactCkStopNoticePeople = new ArrayList<>();
        for (CkOrderRecoveryData ckOrderRecoveryData : ckOrderRecoveryDataList) {
            String serialNumber = ckOrderRecoveryData.getSerialNumber();
            if (serialNumberList.contains(serialNumber)) {
                String feedbackCode = ckOrderRecoveryData.getFeedbackCode();
                if (!stopNumbers.contains(feedbackCode)&&!missNumbers.contains(feedbackCode)) {
                    List<CkStopNoticePerson> ckStopNoticePeople = ckStopNoticePeopleMap.get(serialNumber);
                    ckStopNoticePeople.stream().forEach(ckStopNoticePerson -> {
                        ckStopNoticePerson.setIsDelete((byte)1);
                    });
                    contactCkStopNoticePeople.addAll(ckStopNoticePeople);
                }
            }
        }
        logger.info("在失联表中物理删除开始");
        if (!CollectionUtils.isEmpty(contactCkStopNoticePeople)) {
            ckStopNoticePersonService.updateForeach(contactCkStopNoticePeople);
        }
        logger.info("在失联表中物理删除结束");
        logger.info("判断失联表中是否出现成功联系结束");
        logger.info("判断未接听连续失联三次为停催开始");
        List<CkStopNoticePerson> threes = new ArrayList<>();

        for (CkStopNoticePerson ckStopNoticePerson : ckStopNoticePeople2) {
            String serialNumber = ckStopNoticePerson.getSerialNumber();
            if (serialNumberList.contains(serialNumber)) {
                List<CkStopNoticePerson> ckStopNoticePeople = ckStopNoticePeopleMap.get(serialNumber);
                if (ckStopNoticePeople.size() > 2) {
                    String dataTime = ckStopNoticePerson.getDataTime();
                    List<String> twoDateBefore = getTwoDateBefore(dataTime);
                    int i=0;
                    for (CkStopNoticePerson stopNoticePerson : ckStopNoticePeople) {
                        String nDataTime = stopNoticePerson.getDataTime();
                        if (twoDateBefore.contains(nDataTime)) {
                            i+=1;
                        }
                    }
                    if (i == 2) {
                        ckStopNoticePeople.stream().forEach(ckStopNoticePerson1 ->
                        {
                            ckStopNoticePerson1.setType((byte)1);
                            threes.add(ckStopNoticePerson1);
                        });
                    }
                }
            }
        }
        logger.info("存储失联变为停催数据开始");
        if (!CollectionUtils.isEmpty(threes)) {
            ckStopNoticePersonService.updateForeach(threes);
        }
        logger.info("存储失联变为停催数据结束");
        logger.info("判断未接听连续失联三次为停催结束");
        logger.info("处理已接表数据开始");

        Map<String, CkOrderAchievementForm> ckOrderRecoveryDataMap = ckOrderAchievementFormService.selectAll();

        //新增成绩表
        List<CkOrderAchievementForm> addCkOrderAchievementForm = new ArrayList<>();
        //更新成绩表
        List<CkOrderAchievementForm> updateCkOrderAchievementForm = new ArrayList<>();
        for (CkOrderRecoveryData ckOrderRecoveryData : ckOrderRecoveryDataList) {
            String customerId = ckOrderRecoveryData.getCustomerId();
            if (ckOrderRecoveryDataMap.get(customerId) == null) {
                CkOrderAchievementForm ckOrderAchievementForm = new CkOrderAchievementForm();
                ckOrderAchievementForm.setCollectorId(customerId);
                String customerServiceName = ckOrderRecoveryData.getCustomerServiceName();
                ckOrderAchievementForm.setCollectorName(customerServiceName);
                ckOrderAchievementForm.setAmountRecovered("0");
                ckOrderAchievementForm.setDate(format);
                ckOrderAchievementForm.setNumberOfCasesHandled(1);
                ckOrderRecoveryDataMap.put(customerId,ckOrderAchievementForm);
                addCkOrderAchievementForm.add(ckOrderAchievementForm);
            } else {
                CkOrderAchievementForm ckOrderAchievementForm = ckOrderRecoveryDataMap.get(customerId);
                Integer numberOfCasesHandled = ckOrderAchievementForm.getNumberOfCasesHandled();
                numberOfCasesHandled+=1;
                ckOrderAchievementForm.setNumberOfCasesHandled(numberOfCasesHandled);
                ckOrderRecoveryDataMap.put(customerId,ckOrderAchievementForm);
                updateCkOrderAchievementForm.add(ckOrderAchievementForm);
            }
        }
        logger.info("存储成绩表开始");
        if (!CollectionUtils.isEmpty(addCkOrderAchievementForm)) {
            ckOrderAchievementFormService.insertForeach(addCkOrderAchievementForm);
        }
        logger.info("存储成绩表结束");
        logger.info("更新成绩表开始");
        if (!CollectionUtils.isEmpty(updateCkOrderAchievementForm)) {
            ckOrderAchievementFormService.updateForeach(updateCkOrderAchievementForm);
        }
        logger.info("更新成绩表结束");
        logger.info("存储已接听表开始");
        if (!CollectionUtils.isEmpty(ckOrderRecoveryDataList)) {
            ckOrderRecoveryDataService.insertForeach(ckOrderRecoveryDataList);
        }
        logger.info("存储已接听表结束");
        logger.info("处理已接表数据结束");
        logger.info("存储未接听表开始");
        if (!CollectionUtils.isEmpty(ckOrderNotDialedList)) {
            ckOrderNotDialedService.insertForeach(ckOrderNotDialedList);
        }
        logger.info("存储未接听表结束");
        logger.info("存储停催表和失联表开始");
        //失联表查询前期是否以变为已失联
     /*  Set<String> ckStopNoticePeople2SerialNumbers = new HashSet<>();
        for (CkStopNoticePerson ckStopNoticePerson : ckStopNoticePeople2) {
            String serialNumber = ckStopNoticePerson.getSerialNumber();
            ckStopNoticePeople2SerialNumbers.add(serialNumber);
        }
        if (!CollectionUtils.isEmpty(ckStopNoticePeople2SerialNumbers)) {
            List<String> outOfContactBySerialNumber = ckStopNoticePersonService.findOutOfContactBySerialNumber(ckStopNoticePeople2SerialNumbers);
            Iterator<CkStopNoticePerson> iterator = ckStopNoticePeople2.iterator();
            while (iterator.hasNext()) {
                CkStopNoticePerson next = iterator.next();
                String serialNumber = next.getSerialNumber();
                if (outOfContactBySerialNumber.contains(serialNumber)) {
                    iterator.remove();
                }
            }
        }*/
        logger.info("失联表存储开始");
        if (!CollectionUtils.isEmpty(ckStopNoticePeople2)) {
            ckStopNoticePersonService.insertForeach(ckStopNoticePeople2);
        }
        logger.info("失联表存储结束");
        logger.info("停催表存储开始");
        if (!CollectionUtils.isEmpty(ckStopNoticePeople1)) {
            ckStopNoticePersonService.insertForeach(ckStopNoticePeople1);
        }
        logger.info("停催表存储结束");
        logger.info("人工客服数据处理结束");
    }

    /**
     * 获取当前日期的前两天的日期
     * @param dataTime
     * @return
     * @throws ParseException
     */
    private List<String> getTwoDateBefore(String dataTime) throws ParseException {
        List<String> twoDates = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(dataTime);
        Calendar one = Calendar.getInstance();
        one.setTime(parse);
        one.set(Calendar.DATE,one.get(Calendar.DATE)-1);
        String oneStr = simpleDateFormat.format(one.getTime());
        twoDates.add(oneStr);
        Calendar two = Calendar.getInstance();
        two.setTime(parse);
        two.set(Calendar.DATE,two.get(Calendar.DATE)-2);
        String twoStr = simpleDateFormat.format(two.getTime());
        twoDates.add(twoStr);
        return twoDates;
    }
}
